package org.zn.note.spring.controller;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.zn.note.spring.dao.jpa.TacoJpaRepository;
import org.zn.note.spring.domain.Order;
import org.zn.note.spring.domain.Taco;

import java.util.Optional;

// @RestController 告诉Spring所有方法返回值直接写入应答体中，而不是放到模型中传给下一个视图用来渲染
// 也可以用 @Controller，然后在每个方法上加上@ResponseBody
// 或者用 @Controller，然后返回ResponseEntiry对象
@RestController
// produces 只处理 Accept头信息包含application/json 的请求
// 如果既支持json，也支持xml
// @RequestMapping(path = "/design", produces = {"application/json", "text/xml"})
@RequestMapping(path = "/design", produces = "application/json")
// 允许跨域访问（应为前后端分离，不在一个机器上）
// 服务器应答添加CORS头信息 （Cross-Origin Resource Sharing，跨域资源共享）
@CrossOrigin(origins = "*")
public class DesignTacoNewController {

    private TacoJpaRepository tacoRepository;

    public DesignTacoNewController(TacoJpaRepository tacoRepository) {
        this.tacoRepository = tacoRepository;
    }

    @GetMapping("/recent")
    public Iterable<Taco> recentTacos() { // 获取并返回最近设计的taco
        PageRequest page = PageRequest.of(0, 12, Sort.by("createdAt").descending());
        return tacoRepository.findAll(page).getContent();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Taco> tacoById(@PathVariable("id") Long id) {
        Optional<Taco> optionalTaco = tacoRepository.findById(id);
        return optionalTaco.isPresent() ?
                new ResponseEntity<>(optionalTaco.get(), HttpStatus.OK) :
                new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
    }

    // consumer指定只能处理请求头Content-type=application/json
    @PostMapping(consumes = "application/json")
    @ResponseStatus(HttpStatus.CREATED)
    public Taco postTaco(@RequestBody Taco taco) {
        return tacoRepository.save(taco);
    }

}
